package com.qf.java2102.qihaonan.hotel.service.impl;

import com.qf.java2102.qihaonan.hotel.dao.IOrderDao;
import com.qf.java2102.qihaonan.hotel.dao.IOrderDetailDao;
import com.qf.java2102.qihaonan.hotel.dao.IUserDao;
import com.qf.java2102.qihaonan.hotel.dao.impl.OrderDaoImpl;
import com.qf.java2102.qihaonan.hotel.dao.impl.OrderDetailDaoImpl;
import com.qf.java2102.qihaonan.hotel.dao.impl.UserDaoImpl;
import com.qf.java2102.qihaonan.hotel.entity.CartItem;
import com.qf.java2102.qihaonan.hotel.entity.ResultVO;
import com.qf.java2102.qihaonan.hotel.pojo.Order;
import com.qf.java2102.qihaonan.hotel.pojo.OrderDetail;
import com.qf.java2102.qihaonan.hotel.pojo.User;
import com.qf.java2102.qihaonan.hotel.service.ICartService;
import com.qf.java2102.qihaonan.hotel.service.IOrderService;
import com.qf.java2102.qihaonan.hotel.utils.JdbcUtils;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.*;

/**
 * @author qhn
 * @version 1.0
 */
public class OrderServiceImpl implements IOrderService {

    private ICartService cartService = new CartServiceImpl();
    private IOrderDao orderDao = new OrderDaoImpl();
    private IOrderDetailDao orderDetailDao = new OrderDetailDaoImpl();
    private IUserDao userDao = new UserDaoImpl();

    /**
     *   返回订单号、订单金额、订单明细数据
     *  用于结账
     * @param cart
     * @return
     */
    @Override
    public ResultVO<Map> generate(Map<Long, CartItem> cart, User user) {

        Map<String, Object> map = new HashMap<>();

        try {
            //取出餐车中数据

            ResultVO<Map<String, Object>> cartMap = cartService.getCart(cart, user);

            JdbcUtils.begin();

            //创建订单
            Order order = new Order();
            order.setOrderId(System.currentTimeMillis() + "");   //订单ID
            order.setUserId(user.getUserId());
            order.setOrderCreateTime(new Date());
            order.setOrderStatus(0);  //0:未支付
            order.setTotalNum((Integer) cartMap.getData().get("totalNum"));
            order.setOrderTotalPrice((BigDecimal) cartMap.getData().get("totalMoney"));
            //保存订单到数据库
            orderDao.save(order);
            Thread.sleep(50);

            //保存订单明细
            List<CartItem> cartItems = (List<CartItem>) cartMap.getData().get("cartItems");

            //List<OrderDetail> orderDetails = new ArrayList<>();

            for (CartItem cartItem : cartItems) {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOrderDetailId(System.currentTimeMillis() + "");  //订单明细ID
                orderDetail.setOrderId(order.getOrderId());   //订单ID
                orderDetail.setFoodId(cartItem.getFoodId());
                orderDetail.setFoodTotalPrice(cartItem.getTotalPrice());
                orderDetail.setNum(cartItem.getNum());
                orderDetail.setOrderDetailCreateTime(new Date());
                orderDetail.setOrderDetailUpdateTime(new Date());
                orderDetailDao.save(orderDetail);
                Thread.sleep(50);
                //订单明细列表
                //orderDetails.add(orderDetail);
            }

            //订单编号
            map.put("orderId", order.getOrderId());
            //订单总金额
            map.put("orderTotalPrice", order.getOrderTotalPrice());
            //订单明细列表
            map.put("orderDetails", cartItems);

            JdbcUtils.commit();
            return ResultVO.ok("保存订单成功", map);
        } catch (SQLException e) {
            e.printStackTrace();
            JdbcUtils.rollback();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.release(JdbcUtils.getConnection());
        }
        return ResultVO.error("保存订单失败");
    }

    @Override
    public ResultVO<String> pay(String orderId, BigDecimal money) {
        try {
            JdbcUtils.begin();
            //1.查询订单支付状态
            Order order = orderDao.findById(orderId);
            if (order.getOrderStatus().intValue() == 1) {
                //已支付，订单已经支付，欢迎下次光临
                return ResultVO.ok("订单已经支付，欢迎下次光临");
            }

            //未支付
            //查询钱够不够
            User payUser = userDao.findById(order.getUserId());
            if (payUser.getBalance().doubleValue() < money.doubleValue()) {
                return ResultVO.ok("余额不足，请线下支付");
            }
            //2.扣钱
            payUser.setBalance(payUser.getBalance().subtract(money));
            userDao.updateBalance(payUser);
            order.setOrderStatus(1);
            //3.修改订单状态为已支付，订单支付成功，欢迎下次光临
            orderDao.updateStatus(order);
            JdbcUtils.commit();
            return ResultVO.ok("订单支付成功，欢迎下次光临");
        } catch (SQLException e) {
            e.printStackTrace();
            JdbcUtils.rollback();
        } finally {
            JdbcUtils.release(JdbcUtils.getConnection());
        }
        return ResultVO.error("订单支付失败");
    }
}
